from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from django.contrib.auth.models import User
from download.models import BacteriaModel, AllDownloadModel, PhageModel, ProPhageModel
from django.conf import settings
import os


class Command(BaseCommand):
    help = 'Init Database'
    bacteriaPath = os.path.join(
        settings.BASE_DIR, "material", "bacteria_v1.list")
    phagePath = os.path.join(settings.BASE_DIR, "material", "phage_v1.list")
    proPhagePath = os.path.join(
        settings.BASE_DIR, "material", "prophage_v1.list")
    allPath = os.path.join(settings.BASE_DIR, "material", "all.list")

    def parse_list_file(self, file_path):
        result = []
        with open(file_path, 'r') as f:
            lines = f.readlines()
            for line in lines:
                parts = line.strip().split(',')
                if len(parts) == 2 and parts[0] and parts[1]:  # 检查是否是非空行
                    result.append({'name': parts[0], 'path': parts[1]})
        return result

    def parse_new_list_file(self, file_path, type):
        file_map = {
            "bacteria": "/home/gop/zelixir/database_final/Download/bacteria_tar_gz",
            "phage": "/home/gop/zelixir/database_final/Download/phage_tar_gz",
            "prophage": "/home/gop/zelixir/database_final/Download/prophage_tar_gz",
        }
        result = []
        is_head = True
        with open(file_path, 'r') as f:
            lines = f.readlines()
            for line in lines:
                if is_head:
                    is_head = False
                    continue
                filename = line.replace("\n", "")
                a = filename.split("\t")
                taxId = ""
                if len(a) == 2 and a[1]:
                    filename, taxId = a[0], a[1].split("_")[1]
                else:
                    filename = a[0]
                result.append(
                    {'name': filename, 'path': f'{file_map[type]}/{filename}.tar.gz', 'tax_id': taxId})
        return result

    @transaction.atomic()
    def handle(self, *args, **options):
        BacteriaModel.objects.all().delete()
        self.print_success("BacteriaModel 数据库已经清空")
        AllDownloadModel.objects.all().delete()
        self.print_success("AllDownloadModel 数据库已经清空")
        PhageModel.objects.all().delete()
        self.print_success("PhageModel 数据库已经清空")
        ProPhageModel.objects.all().delete()
        self.print_success("PhageModel 数据库已经清空")
        self.print_success("Database 数据库已经全部清空")

        bacteriaData = self.parse_new_list_file(self.bacteriaPath, "bacteria")
        for data in bacteriaData:
            name = data["name"]
            path = data["path"]
            taxId = data["tax_id"]
            BacteriaModel.objects.create(name=name, path=path, tax_id=taxId)

        self.print_success(
            f'BacteriaModel 数据库记录插入成功，共 {len(BacteriaModel.objects.all())}')

        phageData = self.parse_new_list_file(self.phagePath, "phage")

        for data in phageData:
            name = data["name"]
            path = data["path"]
            taxId = data["tax_id"]
            PhageModel.objects.create(name=name, path=path, tax_id=taxId)

        self.print_success(
            f'PhageModel 数据库记录插入成功，共 {len(PhageModel.objects.all())}')

        proPhageDta = self.parse_new_list_file(self.proPhagePath, "prophage")

        for data in proPhageDta:
            name = data["name"]
            path = data["path"]
            taxId = data["tax_id"]
            ProPhageModel.objects.create(name=name, path=path, tax_id=taxId)

        self.print_success(
            f'ProPhageModel 数据库记录插入成功，共 {len(ProPhageModel.objects.all())}')

        allData = self.parse_list_file(self.allPath)

        for data in allData:
            name = data["name"]
            path = data["path"]
            AllDownloadModel.objects.create(name=name, path=path)

        self.print_success(
            f'AllDownloadModel 数据库记录插入成功，共 {len(AllDownloadModel.objects.all())}')

    def print_success(self, msg: str):
        self.stdout.write(self.style.SUCCESS(msg))

    def print_error(self, msg: str):
        self.stdout.write(self.style.ERROR(msg))
